/**
 * 编辑器错误边界组件
 *
 * 用于捕获 BlockNote/ProseMirror 相关的错误
 * 防止整个应用崩溃
 */

import React from "react";

interface Props {
  children: React.ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
  errorInfo?: React.ErrorInfo;
}

export class EditorErrorBoundary extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error): State {
    return {
      hasError: true,
      error
    };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("编辑器错误边界捕获到错误:", error, errorInfo);

    this.setState({
      hasError: true,
      error,
      errorInfo
    });

    // 可以在这里上报错误到监控系统
    if (import.meta.env.PROD) {
      // 生产环境可以上报到错误监控服务
      // reportError(error, errorInfo);
    }
  }

  handleReload = () => {
    window.location.reload();
  };

  handleReset = () => {
    this.setState({ hasError: false, error: undefined, errorInfo: undefined });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex items-center justify-center min-h-[400px] bg-red-50 border border-red-200 rounded-lg m-4">
          <div className="text-center space-y-4 p-6">
            <div className="text-6xl mb-4">⚠️</div>
            <h2 className="text-xl font-semibold text-red-800">编辑器出现错误</h2>
            <p className="text-red-600 max-w-md">编辑器遇到了意外错误，这可能是由于数据解析或组件渲染问题导致的。</p>

            {import.meta.env.DEV && this.state.error && (
              <details className="mt-4 p-4 bg-red-100 border border-red-300 rounded text-left text-sm">
                <summary className="cursor-pointer font-medium text-red-800 mb-2">错误详情 (开发环境)</summary>
                <pre className="whitespace-pre-wrap text-red-700 overflow-auto max-h-40">
                  {this.state.error.message}
                  {this.state.error.stack}
                </pre>
              </details>
            )}

            <div className="flex gap-3 justify-center mt-6">
              <button
                onClick={this.handleReset}
                className="px-4 py-2 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
              >
                重试
              </button>
              <button
                onClick={this.handleReload}
                className="px-4 py-2 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors"
              >
                刷新页面
              </button>
            </div>

            <p className="text-sm text-gray-600 mt-4">如果问题持续出现，请联系技术支持</p>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
